import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { HttpService } from "../http/http.service";
import { map } from 'rxjs/operators';
import { LocalStorage } from "./localstorage";

@Injectable({
  providedIn: 'root'
})
export class MenuResolver implements Resolve<any> {

  constructor(private http: HttpService, private router: Router) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    return this.http.get('/bas/menu', { params: '' }).pipe(map(res => {
      if (res.data) {
        window.bottons = res.data.bottons;
        window.menus = res.data.menus;
        window.enums = res.data.enums;
        window.loginUserInfo = res.data.loginUserInfo;
        window.messages = res.data.basMsgs;
        LocalStorage.saveMenus(JSON.stringify(res.data.menus));
        return "1";
      } else {
        this.router.navigate([ '/login' ]);
        return null;
      }
    }));
  }
}
